package com.twu.biblioteca;

import java.util.Dictionary;
import java.util.Enumeration;
import java.util.Hashtable;

/**
 * Created by tinamt on 7/22/14.
 */
public class RentedItems {
    Dictionary<RentalItem, Customer> rentedItems;

    RentedItems() {
        rentedItems = new Hashtable<RentalItem, Customer>();
    }


    public int getSize() {
        return rentedItems.size();
    }

    public boolean isItemAlreadyRented(RentalItem rentalItem) {
        return rentedItems.get(rentalItem) != null;
    }

    public void borrow(Customer customer, RentalItem rentalItem) throws ItemAlreadyBorrowed {
        if (isItemAlreadyRented(rentalItem))
            throw new ItemAlreadyBorrowed();
        rentedItems.put(rentalItem, customer);
    }

    public void returnItem(Customer customer, RentalItem rentalItem) throws ItemHasNotBeenBorrowed {
        try {
            String rentersUsername = rentedItems.get(rentalItem).username;

            if (rentersUsername == null || !rentersUsername.equals(customer.getUsername()))
                throw new ItemHasNotBeenBorrowed();
            rentedItems.remove(rentalItem);
        }catch (NullPointerException e)
        {
            throw new ItemHasNotBeenBorrowed();
        }



    }

    public String seeBorrowedItems() {
        StringBuilder checkOutList = new StringBuilder();
        Enumeration<RentalItem> enumKey = rentedItems.keys();
        while (enumKey.hasMoreElements()) {
            RentalItem item = enumKey.nextElement();
            Customer customer = rentedItems.get(item);
            checkOutList.append(customer.username).append("\t\t");
            checkOutList.append(item.getID()).append("\n");
        }
        return checkOutList.toString();
    }
}
